<template>
  <div v-loading="loading" element-loading-text="拼命加载中">
    <JwChat-index @click="bindClick" :config="config" width="100%" height="50%" scrollType :showRightBox='true'
                  :taleList="list"
                  @enter="bindEnter" @clickTalk="talkEvent"
                  v-model="inputMsg"
                  :toolConfig="tool">
      <template slot="tools">
        <div style="width:20rem;text-align:right;" @click="toolEvent('自定义')">
          <JwChat-icon type="icon-lishi" title="自定义"/>
        </div>
      </template>
      <JwChat-rightbox :config="rightConfig" @click="rightClick"/>
    </JwChat-index>

  </div>
</template>

<script>
export default {
  name: "ChatView",
  data() {
    return {
      getImg: '',
      ws_host: '',
      loading: false,
      realName: "",
      rightConfig: {
        listTip: '当前在线',
        notice: '【公告】文明发言，违者直接剔除 ',
        list: []
      },
      inputMsg: '',
      list: [],
      config: {
        img: '',
        name: '',
        dept: '最牛逼、最帅气',
        //callback: this.bindCover,
      },
      tool: {
        show: ['file', 'history', 'img', ['文件1', '', '美图']],
        //showEmoji: false,不显示表情
        callback: this.toolEvent
      },
    }
  },
  methods: {
    bindClick(play) {
      this.$message.info("功能待开发2");
    },
    talkEvent(type, plyload) {
      this.$message.info("功能待开发");
    },
    rightClick(type) {
      console.log(type.value.name)
    },
    toolEvent() {
      this.$message.info("功能待开发");
    },
    queryContent() {
      this.axios.get("/group/queryContent").then(resp => {
        if (resp.data.statusCode == 200) {
          //console.log(resp.data)
          this.rightConfig.notice = '【公告】' + resp.data.data.content;
        }
      })
    },
    bindEnter(e) {
      const msg = this.inputMsg
      if (!msg) {
        this.$message.error("请输入消息内容");
        return;
      }

      let dt = new Date();
      let y = dt.getFullYear();
      let m = dt.getMonth() + 1;
      let d = dt.getDate();
      let hh = dt.getHours();
      let mm = dt.getMinutes();
      let ss = dt.getSeconds();
      let newDt = `${y}-${m}-${d} ${hh}:${mm}:${ss}`;

      let realName = sessionStorage.getItem("loginName");

      if (!realName) {
        return;
      }

      const msgObj = {
        "date": newDt,
        "text": {'text': e},
        "mine": true,
        "name": realName,
        "img": this.getImg + "/common/getImage"
      }

      //发送
      this.sendAllWebSocket(msgObj);

      //this.list.push(msgObj)
    },

    //发送消息
    sendAllWebSocket(msg) {
      this.axios.post("/chat/sendAllWebSocket", msg).then(resp => {
        if (resp.data.statusCode == 200) {
          // this.$message({
          //   type: 'success',
          //   message: '发送成功'
          // });
        }
      })
    },

    // toolEvent(type, obj) {
    //
    // },
    // talkEvent(play) {
    //
    // },

    initWebSocket() {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage

      // 连接成功
      this.websocket.onopen = this.setOnopenMessage

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage() {
      console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
    },
    setOnopenMessage() {
      console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
    },
    setOnmessageMessage(event) {
      // 根据服务器推送的消息做自己的业务处理
      console.log('服务端返回：' + event.data)
      let msg = JSON.parse(event.data);

      if (msg.status == 2) {
        this.rightConfig.list = [];
        let onlineName = msg.onlineName;
        for (let i = 0; i < onlineName.length; i++) {
          let onl = {};
          if (this.realName == onlineName[i]) {
            onl.name = onlineName[i] + "(自己)";
          } else {
            onl.name = onlineName[i];
          }

          onl.img = this.getImg + "/common/getImage";
          this.rightConfig.list.push(onl);
        }
        return;
      }

      if (this.realName == msg.name) {
        msg.mine = true;
      } else {
        msg.mine = false;
      }
      //保存聊天记录到sessionStorage
      //sessionStorage.setItem("chatInfoList",this.list);
      this.list.push(msg);
    },
    setOncloseMessage() {
      console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
    },
    onbeforeunload() {
      this.closeWebSocket()
    },
    closeWebSocket() {
      this.websocket.close()
    }
  },

  beforeDestroy() {
    this.onbeforeunload()
  },

  created() {
    this.loading = true;
    this.getImg = this.$global_msg.api_host;
    this.ws_host = this.$global_msg.ws_host;
    this.config.img = this.$global_msg.api_host + '/common/getImage';
    this.queryContent();
    //this.list = sessionStorage.getItem("chatInfoList");
    this.realName = sessionStorage.getItem("loginName");
    this.config.name = this.realName;
    const img = this.getImg + '/common/getImage';

    let mine = null;
    if (this.realName == "超级管理员") {
      mine = true;
    } else {
      mine = false;
    }

    const list = [

      {
        "date": "2021/03/02 13:14:21",
        "mine": mine,
        "name": "超级管理员",
        "img": img,
        "text": {'text': '大家好'}
      },
    ]
    this.list = list;

    // WebSocket
    let username = sessionStorage.getItem("username");
    if (!username) {
      return;
    }
    if ('WebSocket' in window) {
      this.websocket = new WebSocket('ws://' + this.ws_host + '/websocket/' + username);
      this.initWebSocket();
    } else {
      alert('当前浏览器 Not support websocket');
    }

    let that = this;
    setTimeout(function () {
      that.loading = false;
    }, 500);
  }
}
</script>

<style scoped>

</style>
